using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using ZSoft.PushServices.Net.DTO;
using Android.Graphics;
using System.Threading.Tasks;
using static Android.Provider.Settings;
using SignalR.Client.Portable;
using static System.Diagnostics.Debug;

namespace ZSoft.PushServices.Android
{
    [Service]
    public class BackgroundService : Service
    {
        const string HOST = "http://localhost:10765/";
        HubConnection _connection;
        IHubProxy _hubProxy;
        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            _connection = new HubConnection(HOST);
            _hubProxy = _connection.CreateHubProxy("NotificationHub");
            _hubProxy.On("RecieveNotificaton", (NotificationDTO dto) =>
            {
                this.CreateNotif(dto.Message);
            });


            this.CreateNotif("Service started");
            _connection.Start().Wait();



            _hubProxy.Invoke("Identified", new ClientInfoDTO()
            {
                AppId = 1223.ToString(),
                DeviceId = Id
            }).Wait();

            return StartCommandResult.Sticky;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }


        private void CreateNotif(string message)
        {
            Notification.Builder builder = new Notification.Builder(this)
                .SetTicker(message)
                    .SetContentTitle(message)
                        .SetContentText(message)
                            .SetSmallIcon(Resource.Drawable.Icon);

            Notification notification = builder.Build();
            NotificationManager manager = GetSystemService(Context.NotificationService) as NotificationManager;
            int id = 0;
            manager.Notify(id, notification);
        }

        private string Id
        {
            get
            {
                return Secure.GetString(this.ContentResolver, Secure.AndroidId);
            }
        }
    }
}